package com.jdpc.weparty.controller

import com.jdpc.weparty.controller.vo.ActivityInfoVo
import com.jdpc.weparty.controller.vo.JsonBody
import com.jdpc.weparty.controller.vo.UserVo
import com.jdpc.weparty.entity.Activity
import com.jdpc.weparty.service.activity.ActivityService
import com.jdpc.weparty.service.activity.generateActivityInfo
import com.jdpc.weparty.service.activity.signup.SignUpActivityService
import com.jdpc.weparty.service.pic.PictureService
import com.jdpc.weparty.service.user.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.*
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import javax.servlet.http.HttpServletResponse

@RestController
class ActivityController {
    @Autowired
    lateinit var activityService: ActivityService

    @Autowired
    lateinit var signUpActivityService: SignUpActivityService

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var pictureService: PictureService

    //根据id获取活动信息
    @GetMapping("/activities/{id}")
    fun getActivity(@PathVariable("id") id: Int): ResponseEntity<*> {
        var a = activityService.findActivity(id)
                ?: return ResponseEntity.badRequest().body(JsonBody(-1, "没有该活动id=$id", Any()))
        var aIf = ActivityInfoVo(a, signUpActivityService.getUserForm(id, true).size)
        return ResponseEntity.ok(JsonBody(0, "成功", aIf))
    }

    //查看某活动所有参与者
    @GetMapping("/activities/{id}/joiners")
    fun getJoiners(@PathVariable("id") id: Int, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {
        val pageable = PageRequest.of(page, size)
        var result = signUpActivityService.getUserForm(id, true, pageable)
        return ResponseEntity.ok(JsonBody(0, "成功", PageImpl<UserVo>(result.content.map {
            UserVo().apply {
                setInfo(it)
            }
        }, PageRequest.of(result.number, result.size), result.totalElements)))
    }

    //为某活动添加一条参加申请
    @PostMapping("/activities/{activityId}/joiners/{userId}")
    fun addApply(@PathVariable("activityId") aId: Int, @PathVariable("userId") uId: Int): ResponseEntity<*> {
        val result = signUpActivityService.signUp(uId, aId)
        if (result.first) {
            var code = -1
            var message = ""
            when (result.second) {
                true -> {
                    message = "已经报名过了，且报名通过了"
                    code = -1
                }
                false -> {
                    message = "已经报名过了，且报名被拒绝了(ㄒoㄒ)"
                    code = -2
                }
                null -> {
                    message = "已经报名过了，但发布者还没开始审核，等一等吧"
                    code = -3
                }
            }
            return ResponseEntity.ok(JsonBody(code, message, Any()))
        }
        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
    }

    //提供主页活动推荐
    @GetMapping("/activities/home")
    fun getActivitiesByOrder(@RequestParam order: String, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {
        val page = when (order) {
//            "default" -> {
//
//            }
            "hotest" -> {
                //按活动开始时间升序排列
                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "startTime")
                activityService.findActivity(true, pageable)

            }
            "latest" -> {
                //按活动开始时间升序排列
                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "startTime")
                activityService.findActivity(true, pageable)
            }
            else -> {
                val pageable = PageRequest.of(page, size)
                activityService.findActivity(true, pageable)
            }
        }

        return ResponseEntity.ok(JsonBody(0, "成功",
                PageImpl<ActivityInfoVo>(page.content.map {
                    it?.let {
                        ActivityInfoVo(it, signUpActivityService.getUserForm(it.id, true).size)
                    }
                }, PageRequest.of(page.number, page.size), page.totalElements)))
    }

    //根据名字检索活动
    @GetMapping("/activities")
    fun getActivitiesByName(@RequestParam name: String/*, @RequestParam kind: ActivityType*/): ResponseEntity<*> {
        return ResponseEntity.ok(JsonBody(0, "成功", activityService.findActivity(name).map {
            ActivityInfoVo(it, signUpActivityService.getUserForm(it.id, true).size)
        }))

    }

    //添加活动
    @PostMapping("/activities")
    fun addNewActivity(@RequestBody info: ActivityInfoVo): ResponseEntity<JsonBody<*>> {
        val activityInfo = generateActivityInfo(info)
        val publisher = userService.getUser(info.publisherId)
        val examiner = userService.pickOneExaminer()
        publisher?.let {

            val id = activityService.publishActivity(activityInfo, it, examiner)
            return ResponseEntity.ok(JsonBody(0, "成功", id))

        } ?: return ResponseEntity.badRequest().body(JsonBody(-1, "未找到发布者", Any()))
    }

    //修改活动信息
    @PutMapping("/activities/{id}")
    fun changeActivityInfo(@PathVariable("id") aId: Int, @RequestBody info: ActivityInfoVo): ResponseEntity<*> {
        val activityInfo = generateActivityInfo(info)
        activityService.changeActivityInfo(aId, activityInfo)
        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
    }

    //上传活动图片
    @PostMapping("/activities/{id}/banner")
    fun uploadBanner(@PathVariable("id") aId: Int, @RequestParam("file", required = false) file: List<MultipartFile>?): ResponseEntity<*> {
        file?.let {
            return ResponseEntity.ok(JsonBody(0, "成功", pictureService.saveBanner(it, aId)))

        }
        return ResponseEntity.badRequest().body(JsonBody(-1, "失败", Any()))
    }

    //获取某活动签到的参与者
    @GetMapping("/activities/{id}/sign")
    fun getSignJoiners(@PathVariable("id") aId: Int, @RequestParam("state") state: Boolean): ResponseEntity<*> {
        val result = signUpActivityService.getSignJoiners(aId, state).map {
            UserVo().apply { setInfo(it) }
        }
        return ResponseEntity.ok(JsonBody(0, "成功", result))
    }

    //获取活动图片
    @GetMapping("/banner/activities/{aId}/{picName}", produces = [MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE])
    fun getBanner(response: HttpServletResponse, @PathVariable("aId") activityId: Int, @PathVariable("picName") picName: String) {
        pictureService.responseBanner(response, picName,"/activities/$activityId")

    }

}